package com.fy.tt.executor.node.sentence.simpleStmt;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.fy.toolhelper.tool.ActionTool;
import com.fy.tt.executor.environment.MyMQ;
import com.fy.tt.executor.environment.PolicyWorker;
import com.fy.tt.executor.node.script.SimpleStmt;
import com.fy.tt.executor.node.word.noun.Band;
import com.fy.tt.executor.node.word.noun.Tool;
import com.fy.tt.executor.node.word.noun.Unit;
import com.fy.tt.executor.node.word.noun.User;
import com.fy.tt.parser.V3Parser;
import com.fy.tt.permission.PolicyAddModel;
import com.fy.tt.utils.BandCore;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class AuthoriseStmt extends SimpleStmt {
    //3点-6点,允许 章三 在 喇叭 帮区执行 喇叭 工具的 发声 部件。
    private User user;
    private Band band;
    private Tool tool;
    private Unit unit;

    private V3Parser.AuthoriseStmtContext ctx;

    public AuthoriseStmt(V3Parser.AuthoriseStmtContext ctx, Map<String, Object> scriptEnvironment) {
          this.ctx=ctx;
        user = new User(ctx.Identifier().get(0).getText(), scriptEnvironment);
        band = new Band(ctx.place().Identifier().getText(), scriptEnvironment);
        tool = new Tool(ctx.Identifier().get(1).getText(), scriptEnvironment);
        if(ctx.Unit()!=null){
            unit = new Unit(ctx.Identifier().get(2).getText(), scriptEnvironment);
        }
    }

    @Override
    public boolean run(String methodName) {
        String httpurl = "http://127.0.0.1:8083/permissionBus/policyPermission/addPolicy";
        //"subject=%s&object=%s&operation=%s&bandID=%s&env=%s&text=%s";
        //todo角色需要去帮区搜索
        String[] roles={"管理员","工者","知者","言者"};
        Set<String> roleSet=new HashSet<>();
        for (int i = 0; i < roles.length; i++) {
            roleSet.add(roles[i]);
        }
        String subjectPolicy;
        if(roleSet.contains(ctx.Identifier(0).getText().trim())){
            subjectPolicy="r.sub.role=='"+ctx.Identifier(0).getText().trim()+"'";;
        }else{
            subjectPolicy="r.sub.name=='"+ctx.Identifier(0).getText().trim()+"'";
        }
        //todo角色需要去帮区搜索
        StringBuilder operation=ctx.Allow()!=null?
                new StringBuilder("can"):new StringBuilder("cannot") ;
        operation.append(ctx.Run().getText()==""?".*":".act");
        //String toolText=ctx.Identifier().get(1).getText().trim();
        String toolText=tool.id;
        String unitText="*";
        StringBuilder object=new StringBuilder(toolText);
        if(ctx.Identifier().size()==3){
            unitText=ctx.Identifier().get(2).getText().trim();
        }
        unitText.replaceAll(" ","");
        object.append("."+unitText);
        StringBuilder env=new StringBuilder();
        if(ctx.timeFrame()!=null){
            String hourStart=ctx.timeFrame().Number(0).getText();
            String hourEnd=ctx.timeFrame().Number(1).getText();
            if(Long.parseLong(hourStart)<=Long.parseLong(hourEnd)){
                env.append("r.env.time.hour>="+hourStart+"&&r.env.time.hour<="+hourEnd);
            }else{
                env.append("(r.env.time.hour>=0&&r.env.time.hour<="+hourEnd+")");
                env.append("||(r.env.time.hour>="+hourStart+"&&r.env.time.hour<=24)");
            }
        }

        String bandID=band.getObjID();
        //bandID.replaceAll(" ","");
//        try {
//            bandID = URLEncoder.encode(bandID, "UTF-8");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
        //httpurl=String.format(httpurl,subjectPolicy,object,operation,bandID,env.toString(),ctx.getText());
        System.out.println("httpurl = " + httpurl);
        Map<String,String> param=new HashMap<>();

        param.put("subject",subjectPolicy);
        param.put("object",object.toString());
        param.put("operation",operation.toString());
        param.put("bandID",bandID);
        param.put("env",env.toString());
        param.put("text",ctx.getText());
        System.out.println("param = " + param.toString());
        PolicyAddModel policy=new PolicyAddModel(subjectPolicy,object.toString(),operation.toString(),bandID,env.toString(),ctx.getText().replaceAll(" ",""));
        try {
            PolicyWorker policyWorker = ActionTool.getBean(PolicyWorker.class);
            policyWorker.addPolicy(policy);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }


//        System.out.println("s2 = " + s2);;
        return true;
    }

}
